<template>
	<view class="city-select-container" :style="popupStyleCom">
		<!-- #ifdef MP-WEIXIN -->
		<custom-navber :title="'城市活动'"></custom-navber>
		<!-- #endif -->
		<view class="city-top-section" :style="{paddingTop:menuObject.top + menuObject.height + 15 +'px'}">
			<view class="ping-30 pt-0">
				<view class="bac-col-fa flex-dir-row ali-item-cen ping-13-25 br-200">
					<text class="iconfont ic-sousuo col-00ba31 fs-40 mr-10"></text>
					<input class="fs-24 w-100" type="text" confirm-type="search" v-model="searchValue"
						placeholder="点击搜索城市" placeholder-style="color:#0a2e365e" @blur="search" />
					<text v-if="searchValue.length" class="iconfont  ic-qingchu fs-40 col-0a2e36" @click="clearIcon" />
				</view>
			</view>
			<view class="heng">
			</view>
			<view class="ping-30 pb-0">
				<view class="fs-30  fw-600">热门城市</view>
				<view class="hot-city-list mt-30 flex-dir-row ali-item-cen flex-x-bet flex-w-wrap">
					<view class="hot-city-item" v-for="(item,index) in hotCity" :key="index"
						@click="hotCityClick(item.code)">
						{{ item.name }}
					</view>
				</view>
			</view>
		</view>
		<view class="heng">
		</view>
		<view class="city-list-container">
			<uni-city-list :options="list" :showSelect="false" @click="cityClick"></uni-city-list>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const _ = db.command;
	const $ = _.aggregate;

	var cache = {};

	const hotCityCacheKey = "uni-city-list.hotCity";

	import uniCityList from "../../components/uni-city-list/uni-city-list"
	export default {
		components: {
			uniCityList
		},
		onLoad() {
			this.getCloudData();
			let hotCity = uni.getStorageSync(hotCityCacheKey);
			if (hotCity) {
				this.hotCity = hotCity;
			}
			const eventChannel = this.getOpenerEventChannel();
			// 监听data事件，获取上一页面通过eventChannel.emit传送到当前页面的数据
			if (eventChannel.on) {
				eventChannel.on('data', (data) => {
					this.hotCity = data.hotCity;
					// 需要缓存
					uni.setStorageSync(hotCityCacheKey, data.hotCity);
				});
			}
		},
		data() {
			return {
				searchValue: "",
				where: {},
				list: [],
				hotCity: [],
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: {
					height: 15,
					top: 0
				},
				// #endif
			}
		},
		methods: {
			_select(cityInfo) {
				const eventChannel = this.getOpenerEventChannel();
				if (eventChannel.emit) eventChannel.emit('select', cityInfo);
				uni.navigateBack();
			},
			search() {
				if (this.searchValue) {
					// 只有搜索的时候才可以搜索到县级市（因为县级市太多了，如果一开始就全部显示组件会卡住）
					this.where = {
						name: new RegExp(this.searchValue),
						type: _.in([1, 2])
					};
				} else {
					this.where = {};
				}
				this.getCloudData();
			},
			getWhere() {
				let {
					where = {}
				} = this;
				return {
					type: 1,
					...where
				}
			},
			// 获取云端数据
			async getCloudData() {
				let where = this.getWhere();
				if (cache[JSON.stringify(where)]) {
					this.list = cache[JSON.stringify(where)];
				}
				let dbRes = await db.collection("opendb-city-china").aggregate()
					.match(where)
					.group({
						_id: "$first_letter",
						data: $.push("$name"),
						value: $.push({
							code: "$code",
							name: "$name",
						})
					})
					.addFields({
						letter: "$_id",
					})
					.sort({
						_id: 1
					})
					.limit(1000)
					.end();
				let rows = dbRes.result.data;
				this.list = rows;
				cache[JSON.stringify(where)] = rows;
			},
			cityClick(e) {
				let name = e.item.name;
				let cityInfo = this.getCityInfo({
					name
				});
				this._select(cityInfo);
			},
			hotCityClick(code) {
				let cityInfo;
				if (code == '000000') {
					cityInfo = {
						code: '000000',
						name: '全国'
					}
				} else {
					cityInfo = this.getCityInfo({
						code
					});
				}

				this._select(cityInfo);
			},
			getCityInfo(obj = {}) {
				let {
					code,
					name
				} = obj;
				let list = [];
				this.list.map((item, index) => {
					list = list.concat(item.value);
				});
				let cityInfo = list.find((item) => {
					return (code && item.code == code) || (name && item.name == name);
				});
				return cityInfo;
			},
			clearIcon() {
				this.searchValue = '';
			},
		},
		computed: {
			popupStyleCom() {
				let systemInfo = uni.getSystemInfoSync();
				let top = systemInfo.safeAreaInsets.top || 0;
				//console.log('systemInfo: ', systemInfo)
				return `height: ${systemInfo.windowHeight}px`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.city-select-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		overflow: hidden;
	}

	.city-top-section {
		flex-shrink: 0;
	}

	.hot-city-item {
		width: 23%;
		border-radius: 10rpx;
		background: #f7f7f7;
		height: 60rpx;
		font-size: 28rpx;
		line-height: 60rpx;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.city-list-container {
		position: relative;
		flex: 1;
		height: 0;
		/* 让flex自动分配高度 */
	}
</style>